package stocc.converter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import stocc.ParserOutputHandler;
import stocc.logger.Level;
import stocc.subject.Subject;
import stocc.subject.View;

import stocc.converter.exceptions.*;

public class Converter implements ParserOutputHandler {

	private List<Subject> slist;
	
	public Converter(){
		slist = new ArrayList<Subject>();
	}
	
	@Override
	public void addSubject(Subject subject) {
		slist.add(subject);
		log("Added subject: " + subject.getName(), Level.INFO);
	}

	@Override
	public void done() throws Exception {
		log("Beginning conversion", Level.INFO);
		
		
		//Build list of views(objects) from subjects
		ObjectBuilder ob = new ObjectBuilder();
		
		//Print views to individual files
		ObjectPrinter op = new ObjectPrinter();
		
		try{
			List<View> vlist = ob.build(slist);
			
			//DEBUG
			//log("View in list: " + vlist.get(0).getName(), Level.DEBUG);
			
			op.print(vlist);
		}catch (NameConflictException e){
			log("NAME CONFLICT, CONVERSION ABORTED", Level.CRITICAL);
			log("The ObjectBuilder failed with the following message:", Level.IMPORTANT);
			log(e.getMessage(), Level.IMPORTANT);
			log("See Troubleshooting: Name conflicts in readme.txt for more information", Level.IMPORTANT);
			throw new Exception("Name conflict");
		}catch (CodeConflictException e){
			log("CODE CONFLICT, CONVERSION ABORTED", Level.CRITICAL);
			log("The ObjectBuilder failed with the following message:", Level.IMPORTANT);
			log(e.getMessage(), Level.IMPORTANT);
			log("See Troubleshooting: Code conflicts in readme.txt for more information", Level.IMPORTANT);
			throw new Exception("Code conflict");
		}catch (VisibilityConflictException e){
			log("VISIBILITY CONFLICT, CONVERSION ABORTED", Level.CRITICAL);
			log("The ObjectBuilder failed with the following message:", Level.IMPORTANT);
			log(e.getMessage(), Level.IMPORTANT);
			log("See Troubleshooting: Visibility conflicts in readme.txt for more information", Level.IMPORTANT);
			throw new Exception("Visibility conflict");
		}catch (IOException e){
			log("Error creating output files", Level.CRITICAL);
			throw new Exception("IO Error");
		}
		
		log("Conversion complete", Level.INFO);
	}

	/**
	 * Logging method, add this to any class that does logging
	 * @param message The message to be logged
	 * @param level The logging level of the message
	 */
	private static void log(String message, stocc.logger.Level level){
		stocc.logger.Logger.getLogger().log(level, "Converter", message);
	}	

}
